#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
// #include <BLE2902.h>
// #include <WString.h>


#include <WiFi.h>

const char *ssid = "esp32c6";
const char *password = "17366269557";

// BLE服务UUID定义
#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

int wifi_status_pin=9;
int ble_status_pin=10;

NetworkServer server(80);
// 全局变量
BLEServer *pServer = NULL;
bool deviceConnected = false;
// BLECharacteristic *pCharacteristic = NULL;
// bool oldDeviceConnected = false;

// 服务器回调类
class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
      Serial.println("ble connected");
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
      Serial.println("ble disconnected");
    }
};

// // 特征值回调类
// class MyCharacteristicCallbacks: public BLECharacteristicCallbacks {
//     void onWrite(BLECharacteristic *pCharacteristic) {
//       // std::string value = pCharacteristic->getValue();
//       String value = pCharacteristic->getValue();
      
//       if (value.length() > 0) {
//         Serial.print("收到数据: ");
//         for (int i = 0; i < value.length(); i++) {
//           Serial.print(value[i]);
//         }
//         Serial.println();
        
//         // 自动回复
//         String reply = "已收到: " + String(value.c_str());
//         pCharacteristic->setValue(reply.c_str());
//         pCharacteristic->notify();
//       }
//     }
// };

void setup() {
  Serial.begin(115200);
  Serial.println("ESP32-C6 start...");
  
  pinMode(wifi_status_pin, OUTPUT);
  pinMode(ble_status_pin, OUTPUT);


  WiFi.begin(ssid, password);
  WiFi.setAutoReconnect(true);

  // 初始化BLE设备
  BLEDevice::init("ESP32-C6-BLE");
  // 创建BLE服务器
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // 创建BLE服务
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // // 创建可读写的特征值
  // pCharacteristic = pService->createCharacteristic(
  //                     CHARACTERISTIC_UUID,
  //                     BLECharacteristic::PROPERTY_READ   |
  //                     BLECharacteristic::PROPERTY_WRITE  |
  //                     BLECharacteristic::PROPERTY_NOTIFY |
  //                     BLECharacteristic::PROPERTY_INDICATE
  //                   );

  // // 添加特征值描述符
  // pCharacteristic->addDescriptor(new BLE2902());
  // pCharacteristic->setCallbacks(new MyCharacteristicCallbacks());

  // // 设置初始值
  // pCharacteristic->setValue("Hello World");

  // 启动服务
  pService->start();

  // // 开始广播
  // BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  // pAdvertising->addServiceUUID(SERVICE_UUID);
  // pAdvertising->setScanResponse(true);
  // pAdvertising->setMinPreferred(0x06);  // 有助于iPhone连接
  // pAdvertising->setMinPreferred(0x12);
  // BLEDevice::startAdvertising();
  
  Serial.println("wait for client connecting...");
}

void loop() {
  /**
  // 处理设备连接状态变化
  if (!deviceConnected && oldDeviceConnected) {
    delay(500); // 给蓝牙栈一点时间
    pServer->startAdvertising(); // 重新开始广播
    Serial.println("开始广播");
    oldDeviceConnected = deviceConnected;
  }
  
  if (deviceConnected && !oldDeviceConnected) {
    oldDeviceConnected = deviceConnected;
  }

  // 从串口读取数据并发送
  if (Serial.available() && deviceConnected) {
    String input = Serial.readStringUntil('\n');
    input.trim();
    
    if (input.length() > 0) {
      pCharacteristic->setValue(input.c_str());
      pCharacteristic->notify();
      Serial.println("发送数据: " + input);
    }
  }
  **/

  NetworkClient client = server.accept();  // listen for incoming clients
  if (client) {                     // if you get a client,
    Serial.println("New Client.");  // print a message out the serial port
    String currentLine = "";        // make a String to hold incoming data from the client
    while (client.connected()) {    // loop while the client's connected
      if (client.available()) {     // if there's bytes to read from the client,
        char c = client.read();  
        uint8_t buf[8];
        size_t size;
        client.read(buf, 8);

      }}}
    client.stop();

    while (1) 
    {
      digitalWrite(wifi_status_pin,WiFi.status() == WL_CONNECTED?HIGH:LOW);  
      digitalWrite(ble_status_pin,deviceConnected?HIGH:LOW);
      delay(500);
    }
}

